package com.huangwei.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Component
@Aspect
public class DataAspect {

    @Around("execution(public * com.huangwei.dao.*.query*(..))")
    public Object setImgUrl(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String contextPath = request.getScheme() + "://"
                + request.getServerName()
                + ":" + request.getServerPort()
                + request.getContextPath() + "/"
                + "images/";
        Object objectList = joinPoint.proceed();
        if (objectList.getClass() == ArrayList.class) {
            List<Object> newObjList = new LinkedList<>();
            ((List<Object>)(objectList)).stream()
                    .forEach(object -> {
                        String json = JSON.toJSONString(object);
                        String newJson = json.replaceAll("(\\w*/\\w*\\.\\w*)",
                                contextPath + "$1");
                        Object obj = JSONObject.parseObject(newJson, object.getClass());
                        newObjList.add(obj);
                    });
            return newObjList;
        } else {
            String json = JSON.toJSONString(objectList);
            String newJson = json.replaceAll("(\\w*/\\w*\\.\\w*)",
                    contextPath + "$1");
            Object obj = JSONObject.parseObject(newJson, objectList.getClass());
            return obj;
        }
    }
}
